﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Description;

namespace ChatForum.WCF
{
    public class REST<TService, TContract> where TService : TContract
    {
        public static ServiceHost Host(IEnumerable<string> baseAddresses, InstanceProvider<TService> instanceProvider)
        {
            return Host(baseAddresses.Select(ba => new Uri(ba)), instanceProvider);
        }
        public static ServiceHost Host(IEnumerable<Uri> baseAddresses, InstanceProvider<TService> instanceProvider)
        {
            //Creating Service Host with baseAddess and service contract
            WebServiceHost host = new WebServiceHost(typeof(TService), baseAddresses.Select(u => new Uri(u, typeof(TService).Name.ToLower())).ToArray());
            //assigning customized instance provider
            host.Description.Behaviors.Add(instanceProvider);

            foreach (string uriScheme in baseAddresses.Where(ba => ba.Scheme == "http").Select(ba => ba.Scheme))
            {
                foreach (WebMessageFormat format in Enum.GetValues(typeof(WebMessageFormat)))
                {
                    host.AddServiceEndpoint(typeof(TContract), new WebHttpBinding(), "rest/" + format.ToString().ToLower())
                        .Behaviors.Add(new WebHttpBehavior() { DefaultOutgoingResponseFormat = format });
                }
            }
            return host;
        }
    }
}
